package com.yxjx.duoxue.course;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.tencent.stat.StatService;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.YxSegment;
import com.yxjx.duoxue.R.id;
import com.yxjx.duoxue.R.layout;
import com.yxjx.duoxue.activities.ActivityIntroductionActivity;
import com.yxjx.duoxue.activities.RichTextHelper;
import com.yxjx.duoxue.course.SchoolIntroductionActivity.ViewPagerAdapter;
import com.yxjx.duoxue.customview.OutScrollView;
import com.yxjx.duoxue.customview.YxDetailedInfoView1;
import com.yxjx.duoxue.customview.YxFoldableListView;
import com.yxjx.duoxue.customview.YxTabHost;
import com.yxjx.duoxue.customview.YxDetailedInfoView1.YxListAdapter1;
import com.yxjx.duoxue.customview.YxFoldableListView.FoldableAdapter;
import com.yxjx.duoxue.customview.YxTabHost.Callback;
import com.yxjx.duoxue.datamodel.DMTeacher;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.utils.UIHelper;

import android.content.AsyncTaskLoader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class TeacherIntroductionActivity extends BaseActionBarActivity {
//	private YxFoldableListView mCourseList;
//	private YxDetailedInfoView1 mAchivement;
//	private YxListAdapter1 mAchiementAdapter;
//	private FoldableAdapter mCourseListAdapter;
//	private YxDetailedInfoView1 mTeacherBackground;
//	private YxListAdapter1 mTeacherBgAdapter;
	private ArrayList<DMCourse> courses;
	
	private OutScrollView mOutScroll;
	private ViewPager pagers;
	private YxTabHost tabs;
	private String teacherId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.fragment_teacher_intro);
		customizeActionBarTitle("老师简介");
		
		View favouriteView = mActionBar.getCustomView().findViewById(R.id.favourite);
		favouriteView.setVisibility(View.GONE);
		
//		mCourseList = (YxFoldableListView) findViewById(R.id.course_list);
//		mCourseListAdapter = mCourseList.new FoldableAdapter<DMCourse>();
//		mCourseList.setAdapter(mCourseListAdapter);
//		
//		mAchivement = (YxDetailedInfoView1) findViewById(R.id.achievement);
//		mAchiementAdapter = mAchivement.new YxListAdapter1();
//		mAchivement.setAdapter(mAchiementAdapter);
//		
//		mTeacherBackground = (YxDetailedInfoView1) findViewById(R.id.background);
//		mTeacherBgAdapter = mTeacherBackground.new YxListAdapter1();
//		mTeacherBackground.setAdapter(mTeacherBgAdapter);
		
		// customize tabs
		mOutScroll = (OutScrollView) findViewById(R.id.scrollView);
		pagers = (ViewPager) findViewById(R.id.pagers);
		pagers.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
		pagers.setOffscreenPageLimit(2);
		tabs = (YxTabHost) findViewById(R.id.head_tabs);
		tabs.customizeLabels(new String[] {
				"老师简介","教学成果", "开设课程"
		});
		tabs.setCallback(new Callback() {

			@Override
			public void tabSelected(int index) {
				pagers.setCurrentItem(index, true);

			}
		});
		pagers.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (arg1 == 0.0) {
					tabs.setTab(arg0);
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		// customize page tabs end
		
		// customize data
		Bundle extra = getIntent().getExtras();
		teacherId = extra.getString(NwUtils.KEY_ID);
		if (!UIHelper.isEmpty(teacherId)) {
			LoadingAsyncTask lat = new LoadingAsyncTask();
			JSONObject params = new JSONObject();
			try {
				params.put(NwUtils.KEY_ID, teacherId);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			lat.execute(NwUtils.REQ_TEACHER_INFO, params.toString());
		}
		
	}
	
	private void dismissLoadingDialog() {
		findViewById(R.id.root).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	private void fillAchiementAdapterData(YxListAdapter1 YxListAdapter1) {
		ArrayList<Integer> itemTypes = new ArrayList<Integer>();
		ArrayList<Object> data = new ArrayList<Object>();
		for (int i = 0; i < 2; i++) {
			itemTypes.add(YxDetailedInfoView1.TYPE_TEXT);
			itemTypes.add(YxDetailedInfoView1.TYPE_IMG);
			data.add(new Object());
			data.add(new Object());
		}
		YxListAdapter1.setData(itemTypes, data);
	}
	
	class LoadingAsyncTask extends AsyncTask<String, Integer, DMTeacher> {

		@Override
		protected DMTeacher doInBackground(String... arg0) {
			DMTeacher teacher = null;
			String url = arg0[0];
			JSONObject jo = null;
			
			try {
				if (!UIHelper.isEmpty(arg0[1])) {
					jo = new JSONObject(arg0[1]);
				}
				teacher = (DMTeacher) NwUtils.requestDataInfo(url, jo, TeacherIntroductionActivity.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return teacher;
		}
		
		@Override
		protected void onPostExecute(DMTeacher result) {
			super.onPostExecute(result);
			
			if (result == null) {
				UIHelper.showTips(mOutScroll, R.string.check_nw_and_try);
				finish();
				return;
			}
			// customize UI.
			UIHelper.asyncLoadCircleImage(
					(ImageView) findViewById(R.id.teacher_icon),
					result.getIconUrl(),
					R.drawable.default_head_icon);
			UIHelper.setText(findViewById(R.id.root), R.id.teacher_name, result.getTeacherName());
			UIHelper.setText(findViewById(R.id.root), R.id.school_name, result.getFullSchoolName());
			
			// customize rich text
			RichTextHelper rh = new RichTextHelper();
			rh.parseHtmlString(result.getTeacherAchievment());
			ArrayList<Object> datas = rh.getData();
			ArrayList<Integer> types = rh.getItemTypes();
//			mAchiementAdapter.setData(types, datas);
			
			setCourses(result.getCoursesArray());
			if (coursesDataChangeNotifier != null) {
				coursesDataChangeNotifier.notifyDataChanged();
			}
			
			// customize teacher background
			rh = new RichTextHelper();
			rh.parseHtmlString(result.getTeacherDesc());
			datas = rh.getData();
			types = rh.getItemTypes();
			
			/// MTA stat start
			Properties prop = StatHelper.getBasicProp(TeacherIntroductionActivity.this);
			prop.put(StatHelper.KEY_TEACHER, "" + result.getId());
			prop.put(StatHelper.KEY_SCHOOL, result.getFullSchoolName());
			StatService.trackCustomKVEvent(TeacherIntroductionActivity.this, "event_teacher_item_show", prop);
			/// MTA stat end
			
			UIHelper.resetScroll(TeacherIntroductionActivity.this, R.id.scrollView);
			// dismiss loading dialog.
			dismissLoadingDialog();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		// 在onResume时，重新设置内嵌控件的高度。
		// pagers的高度应该为outer的高度减去tabs的高度
		pagers.post(new Runnable() {
			@Override
			public void run() {
				int outHeight = mOutScroll.getHeight();
				int tabHeight = tabs.getHeight();
				int innerWidth = pagers.getWidth();
				pagers.getLayoutParams().width = innerWidth;
				pagers.getLayoutParams().height = outHeight - tabHeight;
				pagers.invalidate();
			}
		});
	}
	
	public Observee getCoursesDataChangeNotifier() {
		return coursesDataChangeNotifier;
	}

	public void setCoursesDataChangeNotifier(Observee coursesDataChangeNotifier) {
		this.coursesDataChangeNotifier = coursesDataChangeNotifier;
	}

	public ArrayList<DMCourse> getCourses() {
		return courses;
	}

	public void setCourses(ArrayList<DMCourse> courses) {
		this.courses = courses;
	}

	public class ViewPagerAdapter extends FragmentStatePagerAdapter  {

		public ViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Fragment ret = null;
			Bundle bundle = new Bundle();
			int layoutId;
			if (position == 0) {
				layoutId = R.layout.segment_h5;
				bundle.putString(YxSegment.KEY_URL, NwUtils.URL_TEACHER_DESC + teacherId);
			} else if (position == 1) {
				layoutId = R.layout.segment_h5;
				bundle.putString(YxSegment.KEY_URL, NwUtils.URL_TEACHER_ACHIEVE + teacherId);
			} else {
				layoutId = R.layout.segment_course_list;
			}
			YxSegment fragment = YxSegment.getSegment(layoutId, bundle);
			return fragment;
		}

		@Override
		public int getCount() {
			return 3;
		}
	}
	
	private Observee coursesDataChangeNotifier;
}
